//
//  NDRequestManager.swift
//  NyamanDana
//
//  Created by 李永彬 on 2025/10/24.
//

import UIKit

struct NDRequestManager {
    
    typealias Completion<T> = (T?, String, String?) -> Void
    static func requestEnvironment(_ completion: Completion<EnvironmentModel>?) {
        let parameters: [String: Any] = [
            "ploric": "0",
            "billionie": "0",
            "plorclearlyhood": WJAppEnvironment.shared.languageCode
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/chromful",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EnvironmentModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let environment = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(environment, response.clositious, nil)
                        print("获取环境成功: \(String(describing: environment.governmentic))")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取环境JSON解析失败: \(error)")
                }
            case .failure(let error):
                print("获取环境失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestVerificationCode(phoneNumber: String, _ completion: Completion<LoginVerCodeModel>?) {
        let parameters: [String: Any] = [
            "equhigh": phoneNumber,
            "speculfly": RandomStringGenerator.generate(),
            "experiity": RandomStringGenerator.generate()
        ]
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/equhigh",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<LoginVerCodeModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let verCodeModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(verCodeModel, response.clositious, nil)
                        print("获取验证码成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取验证码 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取验证码失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestLogin(phoneNumber: String, code: String, _ completion: Completion<LoginInfoModel>?) {
        let parameters: [String: Any] = [
            "suchform": phoneNumber,
            "pudeable": code,
            "scendative": RandomStringGenerator.generate(),
            "contrcy": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/experiity",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<LoginInfoModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let loginModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(loginModel, response.clositious, nil)
                        print("登录成功")
                        
                        NDUserDefaults.shared.saveText(phoneNumber, for: NDPhoneNumberKey)
                        NDUserDefaults.shared.saveText(loginModel.pur ?? "", for: NDAccountIdentifierKey)
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("登录 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("登录失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestHomeData(_ completion: Completion<HomeDataModel>?) {
        let parameters: [String: Any] = [
            "cepting": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/clositious",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<HomeDataModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let homeDataModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(homeDataModel, response.clositious, nil)
                        print("获取首页数据成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取首页数据 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取首页数据失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestProductApplying( productId: Int, _ completion: Completion<ProductApplyingModel>?) {
        let parameters: [String: Any] = [
            "opisive": "1001",
            "cruitwise": "1000",
            "amourstoplike": "1000",
            "exterior": productId,
            "iry": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/scendative",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<ProductApplyingModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let applyingModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(applyingModel, response.clositious, nil)
                        print("点击申请成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("点击申请 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("点击申请数据失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestOrderDetail( productId: Int, _ completion: Completion<NDOrderDetail>?) {
        let parameters: [String: Any] = [
            "exterior": productId,
            "paginbiganeity": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/contrcy",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<NDOrderDetail>.self, from: data)
                    DispatchQueue.main.async {
                        guard let orderDetail = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(orderDetail, response.clositious, nil)
                        print("获取订单详情")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取订单详情 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取订单详情失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func uploadImageData(imageData: Data, stepType: IDCardStepType, _ completion: Completion<ProductIDCardModel>?) {
        var parameters: [String: String] = [:]
        
        var imageType = "11"
        if stepType == .faceReco {
            imageType = "10"
        }
        
        if WJAppEnvironment.shared.currentCountry == .indonesia {
            parameters = [
                "olig": imageType,
                "polor": "2",
                "pancreaticoture": "",
                "policyfold": "1",
                "boardfic": RandomStringGenerator.generate()
            ]
        } else {
            parameters = [
                "olig": imageType,
                "polor": "2",
                "pancreaticoture": ""
            ]
        }
        
        let uploadEndpoint = NDUploadEndpoint(domain: .api,
                                              path: "/sometimesial/quality",
                                              parameters: parameters,
                                              fileData: imageData,
                                              fileName: "id_card_image.jpg")
        NDNetworkService.shared.upload(uploadEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<ProductIDCardModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let idInfo = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(idInfo, response.clositious, nil)
                        print("上传身份证成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("上传身份证 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("上传身份证失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestSaveIdCardInfo_id(birthday: String,
                                        identifyNum: String,
                                        name: String,
                                        phoneNum: String,
                                        orderNum: String,
                                        productId: Int,
                                        _ completion: Completion<Bool>?) {
        let parameters: [String: Any] = [
            "studenttic": RandomStringGenerator.generate(),
            "underatic": RandomStringGenerator.generate(),
            "aboveress": birthday,
            "comeie": identifyNum,
            "interestacle": name,
            "pressoutside": phoneNum,
            "agyr": orderNum,
            "exterior": "\(productId)"
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/phesfy",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("保存用户信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("保存用户信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存用户信息失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestSaveIdCardInfo(birthday: String,
                                      identifyNum: String,
                                      name: String,
                                      _ completion: Completion<Bool>?) {
        let parameters: [String: Any] = [
            "aboveress": birthday,
            "comeie": identifyNum,
            "interestacle": name,
            "olig": "11",
            "seger": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/sculptosity",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("获取订单详情")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("获取订单详情 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取订单详情失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestCustomerDetailInfo(productId: Int, _ completion: Completion<CustomerDetailInfoModel>?) {
        let parameters: [String: Any] = [
            "exterior": "\(productId)",
            "sperglike": RandomStringGenerator.generate()
        ]

        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/costice",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<CustomerDetailInfoModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let detailInfoModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(detailInfoModel, response.clositious, nil)
                        print("获取用户身份信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取用户身份信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取用户身份信息失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestfollowCurrentOrder(productInfo: NDProductInfo, _ completion: Completion<FollowOrderModel>?) {
        let parameters: [String: Any] = [
            "agyr": productInfo.volvator ?? "",
            "nupticoupleant": productInfo.nupticoupleant ?? "",
            "phylactit": productInfo.phylactit ?? "",
            "futurery": productInfo.futurery ?? "",
            "cochlaffectator": RandomStringGenerator.generate(),
            "cryptability": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/hemerhood",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<FollowOrderModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let followOrderModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(followOrderModel, response.clositious, nil)
                        print("跟进订单成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("跟进订单 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("跟进订单失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestPersonalInfo(productId: Int,
                                  _ completion: Completion<PersonalInfoModel>?) {
        let parameters: [String: Any] = [
            "exterior": "\(productId)"
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/stell",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<PersonalInfoModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let personalInfoModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(personalInfoModel, response.clositious, nil)
                        print("获取用户信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("v JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取用户信息失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestSavePersonalInfo(productId: Int,
                                        energyifies: [Energyify],
                                        _ completion: Completion<Bool>?) {
        
        
        var parameters: [String: Any] = [
            "exterior": "\(productId)",
        ]
    
        for energyifie in energyifies {
            if let shotish = energyifie.jobfy,
               let key = energyifie.granally {
                let type = CommonActionType(value: shotish)
               
                switch type {
                case .button:
                    if let olig = energyifie.olig {
                        parameters[key] = olig
                    }
                case .textField, .address:
                    if let fatheraneity = energyifie.fatheraneity {
                        parameters[key] = fatheraneity
                    }
                }
            }
        }
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/ther",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("保存用户信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("保存用户信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存用户信息失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestAddressInfo(productId: Int,
                                  _ completion: Completion<AddressModel>?) {
        let parameters: [String: Any] = [
            "throughetic": RandomStringGenerator.generate(),
            "foliite": RandomStringGenerator.generate()
        ]

        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/nict",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<AddressModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let addressModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(addressModel, response.clositious, nil)
                        print("地址初始化成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("地址初始化JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("地址初始化失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestContacts(productId: Int,
                              _ completion: Completion<ContactsModel>?) {
        let parameters: [String: Any] = [
            "exterior": "\(productId)",
            "interesting": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/agencyature",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<ContactsModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let contactsModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(contactsModel, response.clositious, nil)
                        print("获取联系人信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取联系人信息JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取联系人信息失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestSaveContactsInfo(productId: Int,
                                        pachists: [Pachist],
                                        _ completion: Completion<Bool>?) {
        
        
        let parameters: [String: Any] = [
            "exterior": "\(productId)",
            "aurth": generateCompactJSON(from: pachists)
        ]
        
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/disitor",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("保存联系人信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("保存联系人信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("保存联系人信息失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    /// 将 Pachist 数组转换为紧凑的 JSON 字符串（无换行符）
    static func generateCompactJSON(from pachists: [Pachist]) -> String {
        // 过滤并映射为字典，移除空值
        let dictArray = pachists.compactMap { pachist -> [String: String]? in
            let dictionary = [
                "pressoutside": pachist.pressoutside,
                "interestacle": pachist.interestacle,
                "piouswise": pachist.piouswise,
                "phemia": pachist.phemia
            ].compactMapValues { $0 }
            
            return dictionary.isEmpty ? nil : dictionary
        }
        
        guard !dictArray.isEmpty else {
            return "[]"
        }
        
        do {
            let jsonData = try JSONSerialization.data(
                withJSONObject: dictArray
                // 不使用任何选项，默认就是紧凑格式
            )
            return String(data: jsonData, encoding: .utf8) ?? "[]"
        } catch {
            print("JSON 序列化失败: \(error)")
            return "[]"
        }
    }
    
    static func requestBankInfo(productId: Int,
                                  _ completion: Completion<BankInfoModel>?) {
        let parameters: [String: Any] = [
            "exterior": "\(productId)"
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/pachist",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<BankInfoModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let bankInfoModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(bankInfoModel, response.clositious, nil)
                        print("获取绑卡信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取绑卡信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取绑卡信息失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestSaveBanksInfo(productId: Int,
                                     bankInfoModel: BankInfoModel,
                                     _ completion: Completion<Bool>?) {

        var parameters: [String: Any] = [
            "exterior": "\(productId)",
        ]
        
        for energyifie in bankInfoModel.energyify {
            if let shotish = energyifie.jobfy,
               let key = energyifie.granally {
                let type = CommonActionType(value: shotish)
               
                switch type {
                case .button:
                    if let olig = energyifie.olig {
                        parameters[key] = olig
                    }
                case .textField, .address:
                    if let fatheraneity = energyifie.fatheraneity {
                        parameters[key] = fatheraneity
                    }
                }
            }
        }
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/olig",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("提交绑卡成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("提交绑卡 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("提交绑卡失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestProductList(orderListSelect: NDOrderDataType, _ completion: Completion<ProductListModel>?) {
        let parameters: [String: Any] = [
            "sceneenne": orderListSelect.tag,
            "stultic": "1",
            "hyparian": "50"
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/trigesim",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<ProductListModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let productListModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(productListModel, response.clositious, nil)
                        print("获取订单列表成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("获取订单列表 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("获取订单列表失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestLoginOut(_ completion: Completion<Bool>?) {
        let parameters: [String: Any] = [
            "ther": RandomStringGenerator.generate(),
            "trusization": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/granally",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("退出登录成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("退出登录 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("退出登录失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestCancelAccount(_ completion: Completion<Bool>?) {
        let parameters: [String: Any] = [
            "onia": RandomStringGenerator.generate()
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/glass",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                // 在这里处理原始 Data
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("注销账号成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("注销账号 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("注销账号失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func requestCalculatorResult(loanAmount: Int,
                                        loanTerm: Int,
                                        rate: Float,
                                        type: LoanDurationType,
                                        _ completion: Completion<CalculatorModel>?) {
        let parameters: [String: Any] = [
            "tenaciistic": loanAmount,
            "mitt": rate,
            "meienne": loanTerm,
            "eightia": type.rawValue,
        ]
        
        print(parameters)
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/governmentic",
            method: .get,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<CalculatorModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let calculatorModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(calculatorModel, response.clositious, nil)
                        print("计算成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("计算JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("计算失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    // 埋点
    static func uploadLocationEvent(locationInfo: NDLocationInfo,
                                    _ completion: Completion<Bool>?) {
  
        let parameters: [String: Any] = [
            "disness": locationInfo.province ?? "",
            "algoent": locationInfo.countryCode ?? "",
            "photshoulderer": locationInfo.country ?? "",
            "admititude": locationInfo.street ?? "",
            "have": locationInfo.latitude,
            "trachyate": locationInfo.longitude,
            "buyard": locationInfo.city ?? "",
            "dipsia": RandomStringGenerator.generate(),
            "floorible": locationInfo.district ?? ""
        ]

        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/cutad",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("上报位置信息成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("上报位置信息 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("上报位置信息失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func uploadTheDeviceDetailInformation(_ completion: Completion<Bool>?) {
        
        var dic: [String: Any] = [:]
        
        let sophyifyDic: [String: Any] = [
            "liveid": NDSystemInfo.storageInfo?.free ?? 0,
            "cosmitive": NDSystemInfo.storageInfo?.total ?? -1,
            "linquture": NDSystemInfo.memoryInfo.total,
            "northorium": NDSystemInfo.memoryInfo.free
        ]
        
        dic["sophyify"] = sophyifyDic
        
        let axillroleaciousDic: [String: Any] = [
            "minuteit": Int(NDSystemInfo.batteryStatus.level * 100),
            "callacle": RandomStringGenerator.generate(),
            "trip": (NDSystemInfo.batteryStatus.charging ? 1 : 0)
        ]
        
        dic["axillroleacious"] = axillroleaciousDic
        
        let sorptshipDic: [String: Any] = [
            "sixaster": NDSystemInfo.systemVersion,
            "cardin": "iPhone",
            "opoter": NDSystemInfo.deviceModel,
            "song": NDSystemInfo.deviceDisplayInfo?.name ?? "",
            "corter": UIScreen.main.bounds.height,
            "collectionee": UIScreen.main.bounds.width,
            "auctless": NDSystemInfo.deviceDisplayInfo?.screenSize ?? ""
        ]
        
        dic["sorptship"] = sorptshipDic
        dic["pordom"] = RandomStringGenerator.generate()
        
        let pentDic: [String: Any] = [
            "cumbivity": 100,
            "legior": "0",
            "verbine": "0",
            "revealie": NDSystemInfo.isYueyuDevice ? 1 : 0,
            "audacihundredia": RandomStringGenerator.generate(),
        ]
        
        dic["pent"] = pentDic

        let managementcyDic: [String: Any] = [
            "factator": NDSystemInfo.timezone,
            "ploric": NDSystemInfo.isProxyEnabled ? 1 : 0,
            "billionie": NDSystemInfo.isVPNConnected ? 1 : 0,
            "treeast": NDSystemInfo.carrierName,
            "porward": DeviceIdentifier.vendorIdentifier,
            "willator": NDSystemInfo.deviceLanguage,
            "perhapsfold": RandomStringGenerator.generate(),
            "specably": RandomStringGenerator.generate(),
            "thelful": NDSystemInfo.currentNetType,
            "camermiss": NDSystemInfo.isPhone ? 1 : 0,
            "groundform": NDSystemInfo.deviceIp,
            "cerebrish": NDSystemInfo.wifiBSSID,
            "cosmetwatchful": NDTrackingTool.shared.currentIDFA ?? ""
        ]
        
        dic["managementcy"] = managementcyDic
        
        var chargelingDic: [String: Any] = [:]
        NDLocationManager.shared.getCurrentWifiInfo { wifiInfo, error in
            let coronacityDic: [String: Any] = [
                "attorney": wifiInfo?.bssid ?? "" ,
                "fast": wifiInfo?.ssid ?? "",
                "cerebrish": wifiInfo?.bssid ?? "",
                "interestacle": wifiInfo?.ssid ?? "",
                "person": RandomStringGenerator.generate()
            ]
            chargelingDic["coronacity"] = [coronacityDic]
            dic["chargeling"] = chargelingDic
            
            let parameters:[String: Any] = [
                "aurth": dic.base64EncodedString() ?? ""
            ]
            
            let baseEndpoint = NDBaseEndpoint(
                domain: .api,
                path: "/sometimesial/politward",
                method: .post,
                parameters: parameters,
                contentType: .formUrlEncoded
            )
            
            NDNetworkService.shared.request(baseEndpoint) { result in
                switch result {
                case .success(let data):
                    do {
                        let decoder = JSONDecoder()
                        let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                        DispatchQueue.main.async {
                            completion?(true, response.clositious, nil)
                            print("设备信息上报详细信息成功")
                        }
                        print("Status: \(response.granally)")
                    } catch {
                        DispatchQueue.main.async {
                            completion?(false, "failed", "failed")
                        }
                        print("设备信息上报详细信息 JSON 解析失败: \(error)")
                    }
                case .failure(let error):
                    print("设备信息上报详细信息失败: \(error)")
                    completion?(false, error.localizedDescription, error.localizedDescription)
                }
            }
        }
    }
    
    static func uploadMarketData(_ completion: Completion<MarketModel>?) {
        let parameters:[String: Any] = [
            "porward": DeviceIdentifier.vendorIdentifier,
            "special": RandomStringGenerator.generate(),
            "cosmetwatchful": NDTrackingTool.shared.currentIDFA ?? ""
        ]

        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/majorization",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<MarketModel>.self, from: data)
                    DispatchQueue.main.async {
                        guard let marketModel = response.aurth else {
                            completion?(nil, response.clositious, "failed")
                            return
                        }
                        completion?(marketModel, response.clositious, nil)
                        print("google_market上报成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(nil, "failed", "failed")
                    }
                    print("google_market上报 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("google_market上报失败: \(error)")
                completion?(nil, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func uploadMaiDian(maiDianType: MaiDianType,
                              productId: Int?,
                              orderNum: String?,
                              startTimeStamp: Int,
                              endTimeStamp: Int,
                              _ completion: Completion<Bool>?) {
        let parameters:[String: Any] = [
            "castamongious": productId.map { "\($0)" } ?? "",
            "create": maiDianType.rawValue,
            "volvator": orderNum ?? "",
            "whatation": DeviceIdentifier.vendorIdentifier,
            "maybefic": NDTrackingTool.shared.currentIDFA ?? "",
            "trachyate": NDUserDefaults.shared.retrieveFloat(for: NDCoordinateLngKey) ?? "",
            "have": NDUserDefaults.shared.retrieveFloat(for: NDCoordinateLatKey) ?? "",
            "readyic": "\(startTimeStamp)",
            "pupent": "\(endTimeStamp)"
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/staff",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("上报埋点\(maiDianType.rawValue)成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("上报埋点\(maiDianType.rawValue) JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("上报埋点\(maiDianType.rawValue)失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
    
    static func uploadContactsInformation(aurth: String, _ completion: Completion<Bool>?) {
        let parameters:[String: Any] = [
            "olig": "3",
            "prevent": RandomStringGenerator.generate(),
            "evenness": RandomStringGenerator.generate(),
            "aurth": aurth
        ]
        
        let baseEndpoint = NDBaseEndpoint(
            domain: .api,
            path: "/sometimesial/six",
            method: .post,
            parameters: parameters,
            contentType: .formUrlEncoded
        )
        
        NDNetworkService.shared.request(baseEndpoint) { result in
            switch result {
            case .success(let data):
                do {
                    let decoder = JSONDecoder()
                    let response = try decoder.decode(NDResponse<EmptyTemp>.self, from: data)
                    DispatchQueue.main.async {
                        completion?(true, response.clositious, nil)
                        print("上报通讯录成功")
                    }
                    print("Status: \(response.granally)")
                } catch {
                    DispatchQueue.main.async {
                        completion?(false, "failed", "failed")
                    }
                    print("上报通讯录 JSON 解析失败: \(error)")
                }
            case .failure(let error):
                print("上报通讯录失败: \(error)")
                completion?(false, error.localizedDescription, error.localizedDescription)
            }
        }
    }
}

enum MaiDianType : String {
    case loginIn = "1"
    case IdCard = "2"
    case faceCard = "3"
    case personalCard = "4"
    case contactCard = "6"
    case bankCard = "7"
    case startLoan = "8"
    case endLoan = "9"
}

enum LoanDurationType : Int, RawRepresentable {
    case month = 0
    case year = 1
    
    init?(rawValue: Int) {
        switch rawValue {
        case 0:
            self = .month
        case 1:
            self = .year
        default:
            self = .month
        }
    }
    
    init?(str: String) {
        switch str {
        case "Month":
            self = .month
        case "Year":
            self = .year
        default:
            self = .month
        }
    }
    
    var title: String {
        switch self {
        case .month:
            return "Month"
        case .year:
            return "Year"
        }
    }
}
